//
//  ImageTools.swift
//  TheWatermark
//
//  Created by sharui on 2021/6/3.
//

import Foundation
import SwiftUI

func creatSampleImage(image:NSImage, dataSource: WatermarkData) -> NSImage {
    let height = pow(image.size.height,2)
    let width  = pow(image.size.width,2)
    let maxWidth = Int(sqrt(width + height))
    let maxSize = CGSize(width: maxWidth, height: maxWidth)
    let image2 =  private_creatSampleImage(imageSize: maxSize,dataSource:dataSource)
    return image2
}

func downImage(image:NSImage, dataSource: WatermarkData,newImage: @escaping (NSImage)->(Void)) -> Void{
    let height = pow(image.size.height,2)
    let width  = pow(image.size.width,2)
    let maxWidth = Int(sqrt(width + height))
    let maxSize = CGSize(width: maxWidth, height: maxWidth)
    let image2 =  private_creatSampleImage(imageSize: maxSize,dataSource:dataSource)
    addImage(image: image, fontImage: image2,newImage: newImage)
}


private func private_creatSampleImage(imageSize size: CGSize, dataSource: WatermarkData) -> NSImage {
    let str = NSString(string: dataSource.text)
    
    var imageSize = size
    if size.equalTo(.zero) {
        imageSize = CGSize(width: 500, height: 500)
    }
    
    let img = NSImage(size: imageSize)
    img.lockFocus()
    let ctx = NSGraphicsContext.current
    ctx?.imageInterpolation = .high
    
    var minX: CGFloat = 0
    var minY: CGFloat = 0
    
 
    while minX < imageSize.width || minY < imageSize.height {
        var strSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat(dataSource.textFontSize) + 10)
        let attributes = [NSAttributedString.Key.foregroundColor : (dataSource.randomTextColor ? NSColor.random(alpha: 0.2) :NSColor(dataSource.textColor)),
                          NSAttributedString.Key.font : dataSource.randomTextFont ? NSFont.random() : NSFont.systemFont(ofSize: CGFloat(dataSource.textFontSize))]
        strSize = str.boundingRect(with:strSize, options: [.usesLineFragmentOrigin,.usesFontLeading], attributes: attributes).size
        
        if minX > imageSize.width{
            minX = 0
            minY = minY + strSize.height + CGFloat(dataSource.textVerticalSpace)
        }
        
        str.draw(with: NSRect(x: minX, y: minY, width: strSize.width, height: strSize.height),
                 options: NSString.DrawingOptions.usesLineFragmentOrigin,
                 attributes:attributes)
        
        minX = minX + strSize.width +  CGFloat(dataSource.textHorizontalSpace)
    }
    img.unlockFocus()
    return img.rotated(by: CGFloat(dataSource.textAngle))
}


func creatImage(test: String, imageSize: CGSize, alpha:Double = 0.2) -> NSImage {
    let img = NSImage(size: imageSize)
    img.lockFocus()
    let ctx = NSGraphicsContext.current
    ctx?.imageInterpolation = .high
    
    
    var minX: CGFloat = 0
    var minY: CGFloat = 0
    let strSize = CGSize(width: 200, height: 100);

    while minX < imageSize.width - strSize.width || minY < imageSize.height - strSize.height {
        if minX > imageSize.width - strSize.width{
            minX = 0
            minY = minY + strSize.height;
        }
        
        let str = NSString(string: test)
        
        str.draw(with: NSRect(x: minX, y: minY, width: strSize.width, height: strSize.height),
                 options: NSString.DrawingOptions.usesLineFragmentOrigin,
                 attributes:[NSAttributedString.Key.foregroundColor : NSColor.random(alpha: CGFloat(alpha)),
                             NSAttributedString.Key.font : NSFont.random()])
        
        minX = minX + strSize.width;
    }
    
    img.unlockFocus()
    
    return img
}

extension NSImage {
    
    func tranfrom() ->Data? {
        let imageData = self.tiffRepresentation!
        let imageRep = NSBitmapImageRep.init(data:imageData)
        imageRep?.size = self.size
        let dict = [NSBitmapImageRep.PropertyKey.compressionFactor: 0]
        let imageData1 = imageRep?.representation(using: NSBitmapImageRep.FileType.jpeg, properties: dict)
       return imageData1
     
    }
    /// Rotates the image by the specified degrees around the center.
    /// Note that if the angle is not a multiple of 90°, parts of the rotated image may be drawn outside the image bounds.
    func rotated(by angle: CGFloat) -> NSImage {
        let img = NSImage(size: self.size, flipped: false, drawingHandler: { (rect) -> Bool in
            let (width, height) = (rect.size.width, rect.size.height)
            let transform = NSAffineTransform()
            transform.translateX(by: width / 2, yBy: height / 2)
            transform.rotate(byDegrees: angle)
            transform.translateX(by: -width / 2, yBy: -height / 2)
            transform.concat()
            self.draw(in: rect)
            return true
        })
        img.isTemplate = self.isTemplate // preserve the underlying image's template setting
        return img
    }
}

func addImage(image: NSImage,fontImage: NSImage,  newImage: @escaping (NSImage)->(Void)) -> Void{
    DispatchQueue.global().async {
        let width = image.size.width
        let height = image.size.height
        let img = NSImage(size: CGSize(width: width, height: height))
        img.lockFocus()
        let ctx = NSGraphicsContext.current
        
        ctx?.imageInterpolation = .default
        
        let newRect = NSMakeRect(0, 0, image.size.width, image.size.height)
        
        image.draw(in: newRect)
        let x = (image.size.width - fontImage.size.width)/2
        let y = (image.size.height - fontImage.size.height)/2
        fontImage.draw(in: CGRect(x: x, y: y, width: fontImage.size.width, height: fontImage.size.width))
        img.unlockFocus()
        newImage(img)
    }
        
    
//    UIGraphicsBeginImageContext(image1.size);
    
//    UIGraphicsBeginImageContext()
    
}

//- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 {
//    UIGraphicsBeginImageContext(image1.size);
//
//    // Draw image1
//    [image1 drawInRect:CGRectMake(0, 0, image1.size.width, image1.size.height)];
//
//    // Draw image2
//    [image2 drawInRect:CGRectMake(0, 0, image2.size.width, image2.size.height)];
//
//    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
//
//    UIGraphicsEndImageContext();
//
//    return resultingImage;
//}

extension NSFont {
    class func random() -> NSFont {
        let random = CGFloat(Int(arc4random_uniform(100)) % 10)
        return NSFont.systemFont(ofSize: random + 10)
        
    }
}

extension NSColor {
    class func random(alpha: CGFloat) -> NSColor {
        return NSColor(red: CGFloat(drand48()), green: CGFloat(drand48()), blue: CGFloat(drand48()), alpha: alpha)
    }
}
